import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Send, Bot, User } from 'lucide-react';
import { chatApi } from '../lib/api';
import { supabase } from '../lib/supabase';

interface Message {
  id: number;
  role: 'user' | 'ai';
  content: string;
  created_at: string;
}

interface ChatRoom {
  id: number;
  room_number: number;
  status: string;
  created_at: string;
}

function ChatRoom() {
  const { roomNumber } = useParams<{ roomNumber: string }>();
  const navigate = useNavigate();
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isGameStarted, setIsGameStarted] = useState(false);
  const [isGameEnded, setIsGameEnded] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [roomId, setRoomId] = useState<number | null>(null);
  const [chatRooms, setChatRooms] = useState<ChatRoom[]>([]);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    const fetchRoom = async () => {
      const { data } = await supabase
        .from('chat_rooms')
        .select('id')
        .eq('room_number', roomNumber)
        .maybeSingle();

      if (data) {
        setRoomId(data.id);
        loadMessages(data.id);
      }
    };

    if (roomNumber) {
      fetchRoom();
    }
  }, [roomNumber]);

  useEffect(() => {
    loadChatRooms();
  }, []);

  const loadChatRooms = async () => {
    const { data } = await supabase
      .from('chat_rooms')
      .select('*')
      .order('created_at', { ascending: false });

    if (data) {
      setChatRooms(data as ChatRoom[]);
    }
  };

  const loadMessages = async (id: number) => {
    const { data } = await supabase
      .from('chat_messages')
      .select('*')
      .eq('room_id', id)
      .order('created_at', { ascending: true });

    if (data) {
      setMessages(data as Message[]);

      if (data.length > 0) {
        setIsGameStarted(true);
        const lastMessage = data[data.length - 1];
        if (lastMessage.content.includes('游戏已结束')) {
          setIsGameEnded(true);
        }
      }
    }
  };

  const handleStartGame = async () => {
    if (!roomNumber || !roomId) return;

    setIsSending(true);
    try {
      const aiResponse = await chatApi.sendMessage(Number(roomNumber), '开始');

      const userMessage = { role: 'user' as const, content: '开始', room_id: roomId };
      const aiMessage = { role: 'ai' as const, content: aiResponse, room_id: roomId };

      await supabase.from('chat_messages').insert([userMessage, aiMessage]);

      await loadMessages(roomId);
      await loadChatRooms();
      setIsGameStarted(true);

      if (aiResponse.includes('游戏已结束')) {
        setIsGameEnded(true);
      }
    } catch (error) {
      console.error('Error starting game:', error);
    } finally {
      setIsSending(false);
    }
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim() || !roomNumber || !roomId || isSending) return;

    const userInput = inputValue.trim();
    setInputValue('');
    setIsSending(true);

    try {
      const aiResponse = await chatApi.sendMessage(Number(roomNumber), userInput);

      const userMessage = { role: 'user' as const, content: userInput, room_id: roomId };
      const aiMessage = { role: 'ai' as const, content: aiResponse, room_id: roomId };

      await supabase.from('chat_messages').insert([userMessage, aiMessage]);

      await loadMessages(roomId);
      await loadChatRooms();

      if (aiResponse.includes('游戏已结束')) {
        setIsGameEnded(true);
        await supabase
          .from('chat_rooms')
          .update({ status: 'ended' })
          .eq('id', roomId);
      }
    } catch (error) {
      console.error('Error sending message:', error);
    } finally {
      setIsSending(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleRoomClick = (room: ChatRoom) => {
    navigate(`/chat/${room.room_number}`);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex">
      <aside className="w-64 bg-white border-r-2 border-slate-200 flex flex-col shadow-lg">
        <div className="p-4 border-b-2 border-slate-200">
          <h2 className="text-xl font-bold text-slate-800">历史对话</h2>
        </div>

        <div className="flex-1 overflow-y-auto">
          {chatRooms.map((room) => (
            <button
              key={room.id}
              onClick={() => handleRoomClick(room)}
              className={`w-full text-left px-4 py-3 border-b border-slate-100 hover:bg-slate-50 transition-colors ${
                String(room.room_number) === roomNumber ? 'bg-slate-100' : ''
              }`}
            >
              <p className="font-medium text-slate-800">对话 {room.room_number}</p>
              <p className="text-xs text-slate-500 mt-1">
                {new Date(room.created_at).toLocaleString('zh-CN')}
              </p>
            </button>
          ))}
        </div>
      </aside>

      <div className="flex-1 flex flex-col">
        <header className="bg-white border-b-2 border-slate-200 px-6 py-4 shadow-sm">
          <h1 className="text-3xl font-bold text-slate-800">AI 脑筋急转弯</h1>
          <p className="text-slate-600 mt-1">房间号: {roomNumber}</p>
        </header>

        <div className="flex-1 px-4 py-6 flex flex-col overflow-hidden">
          <div className="flex-1 overflow-y-auto mb-4 space-y-4">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`flex items-start gap-3 ${
                  message.role === 'user' ? 'flex-row-reverse' : ''
                }`}
              >
                <div
                  className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${
                    message.role === 'ai'
                      ? 'bg-blue-500 text-white'
                      : 'bg-slate-500 text-white'
                  }`}
                >
                  {message.role === 'ai' ? <Bot size={20} /> : <User size={20} />}
                </div>

                <div
                  className={`max-w-xl px-4 py-3 rounded-2xl shadow-sm ${
                    message.role === 'ai'
                      ? 'bg-white border-2 border-slate-200'
                      : 'bg-slate-700 text-white'
                  }`}
                >
                  <p className="whitespace-pre-wrap break-words">{message.content}</p>
                </div>
              </div>
            ))}
            <div ref={messagesEndRef} />
          </div>

          <div className="bg-white rounded-2xl border-2 border-slate-200 p-4 shadow-lg space-y-3">
            <div className="flex gap-2">
              <button
                onClick={handleStartGame}
                disabled={isGameStarted || isSending}
                className="px-6 py-2 bg-green-500 text-white rounded-lg font-semibold hover:bg-green-600 disabled:bg-slate-300 disabled:cursor-not-allowed transition-colors"
              >
                开始
              </button>
              <button
                disabled={isGameEnded || !isGameStarted}
                className="px-6 py-2 bg-red-500 text-white rounded-lg font-semibold hover:bg-red-600 disabled:bg-slate-300 disabled:cursor-not-allowed transition-colors"
              >
                结束游戏
              </button>
            </div>

            <div className="flex gap-2">
              <input
                type="text"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="请输入内容"
                disabled={!isGameStarted || isGameEnded || isSending}
                className="flex-1 px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-blue-500 disabled:bg-slate-100 disabled:cursor-not-allowed transition-colors"
              />
              <button
                onClick={handleSendMessage}
                disabled={!inputValue.trim() || !isGameStarted || isGameEnded || isSending}
                className="px-8 py-3 bg-blue-500 text-white rounded-xl font-semibold hover:bg-blue-600 disabled:bg-slate-300 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
              >
                <Send size={20} />
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default ChatRoom;
